<template>
  <div class="app-container">
    <!-- 表格-条件筛区域  -->
    <div class="filter-container">
      <el-input placeholder="请输入课程名称" v-model="searchParam.SEARCH_LIKE_course_name" clearable style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter"> 搜索 </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-plus" @click="handleCreate"> 新增 </el-button>
    </div>

    <!-- 表格-内容区域 -->
    <el-table v-loading="listLoading" :key="tableKey" :data="tableList" border fit highlight-current-row style="width: 100%;">
      <el-table-column v-for="column in columns" :key="column.prop"
                       :prop="column.prop"
                       :label="column.label"
                       :width="column.width"
                       :align="column.align?column.align:'center'"
                       :min-width="column.minWidth"
                       :sortable="column.sortable"
                       :fixed="column.fixed"
                       :type="column.type" :formatter="column.formatter">
        <template slot-scope="scope">
          <!-- 行内显示图片 -->
          <img v-if="column.imgFlag==true" :src=" scope.row[column.prop].indexOf('http') >-1 ?  scope.row[column.prop] : ( CMBASE.baseFileContext + scope.row[column.prop] ) " width="60" height="60" class="img"/>
          <!-- 行内显示开关按钮 -->
          <el-switch v-else-if="column.switchFlag==true" v-model="scope.row[column.prop]" :active-value="1" :inactive-value="0"  disabled />
          <!-- 行内显示tag标签 -->
          <span  v-else-if="column.tagFlag==true">
                        <span v-for="item in column.tagFormatter" :key="item.value" >
                            <el-tag v-if="item.value==scope.row[column.prop]"   :type="item.type">{{item.text}}</el-tag>
                        </span>
                    </span>
          <!-- 行内格式自定义 -->
          <span v-else-if="column.formatter">{{column.formatter(scope.row)}}</span>
          <!--默认显示文本-->
          <span v-else>{{scope.row[column.prop]}}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="260" class-name="small-padding" fixed="right" >
        <template slot-scope="scope">
          <p>
            <el-button type="text"  icon="el-icon-edit" class="el-button--primary" v-if="scope.row.courseForm === '1' && scope.row.type==='1' "  @click="handleInsertItem(scope.row)"> 章节设置 </el-button>
            <el-button type="text"  icon="el-icon-edit" class="el-button--primary" v-if="scope.row.type ==='1' "  @click="handleSignUp(scope.row)"> 报名人数 </el-button>
            <el-button type="text"  icon="el-icon-edit" class="el-button--primary" v-if="scope.row.type !=='1'"  @click="handlePlan(scope.row)"> 开课计划 </el-button>
          </p>
          <p>
            <el-button type="text"  icon="el-icon-edit" class="el-button--primary"  @click="handleUpdate(scope.row)"> 编辑 </el-button>
            <el-button type="text"  icon="el-icon-delete"   class="el-button--danger"  @click="handleDelete(scope.row)"> 删除 </el-button>
            <el-button type="text" icon="el-icon-edit" class="el-button--primary" @click="handleDiscount(scope.row)">生成折扣链接</el-button>
          </p>
        </template>
      </el-table-column>
    </el-table>

    <!-- 表格-页脚区域 -->
    <pagination v-show="tableTotal>0" :total="tableTotal" :page.sync="pageRequest.pageNum" :limit.sync="pageRequest.pageSize" @pagination="getList"/>

    <!--新增编辑界面-->
    <el-dialog :title="operation?'新增':'编辑'" width="75%" height="auto" top="5vh" :visible.sync="dialogFormVisible" :close-on-click-modal="false" v-loading="dataFormLoading">
      <el-form :model="dataForm" label-width="140px" :rules="dataFormRules" ref="dataForm" style="width: 98%;alignItems:center;">
        <el-row>
          <el-col :span="12">
            <el-form-item label="课程名称" prop="courseName">
              <el-input v-model="dataForm.courseName" type="text" show-word-limit  maxlength="32"  auto-complete="off" placeholder="请输入课程名称"/>
            </el-form-item>
            <el-form-item label="课程封面(PC)" prop="courseImg">
              <cm-upload v-model="dataForm.courseImg" auto-complete="off" placeholder="请输入课程封面"/>
              <p style="color: red">270px * 155px</P>
            </el-form-item>
            <el-form-item label="课程封面(Mobile)" prop="courseImgMobile">
              <cm-upload v-model="dataForm.courseImgMobile" auto-complete="off" placeholder="请输入课程封面"/>
              <p style="color: red">270px * 155px</P>
            </el-form-item>
            <el-form-item label="是否推荐 " prop="isTop">
              <el-switch v-model="dataForm.isTop" :inactive-value="0"  :active-text="'推荐'"  :active-value="1"  auto-complete="off" />
            </el-form-item>
            <el-form-item label="是否展示 " prop="isTop">
              <el-switch v-model="dataForm.isShow" :inactive-value="0"  :active-text="'展示'"  :active-value="1"  auto-complete="off" />
            </el-form-item>
            <el-form-item label="上课地点" prop="teachAddress">
              <el-input v-model="dataForm.teachAddress" auto-complete="off" placeholder="请输入上课地点"/>
            </el-form-item>
            <el-form-item label="适合群体" prop="suitGroup">
              <el-input v-model="dataForm.suitGroup" auto-complete="off" placeholder="请输入适合群体"/>
            </el-form-item>
            <el-form-item label="课程价格" prop="coursePrice">
              <el-input-number v-model="dataForm.coursePrice" :min="0" auto-complete="off" placeholder="请输入课程价格"/>
            </el-form-item>


          </el-col>
          <el-col :span="12">
            <el-form-item label="课程分类" prop="courseForm">
              <el-radio-group v-model="dataForm.courseForm" @change="updateTypeOptions">
                <el-radio-button :label="'1'">线上</el-radio-button>
                <el-radio-button :label="'2'">线下</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="课程标签" prop="courseLabel">
              <el-select v-model="dataForm.courseLabel" filterable multiple clearable>
                <el-option v-for="item in labelOptions " :key="item.value" :value="item.value" :label="item.label" ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="课程类型" prop="type">
              <el-select v-model="dataForm.type" filterable clearable>
                <el-option v-if="dataForm.courseForm"
                  v-for="item in typeOptions"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="教材名称" prop="courseMaterialName">
              <el-input v-model="dataForm.courseMaterialName" auto-complete="off" placeholder="请输入教材名称"/>
            </el-form-item>
            <el-form-item label="教材下载链接" prop="courseMaterial">
              <UploadFile v-if="dialogFormVisible"  v-model="dataForm.courseMaterial" :value="dataForm.courseMaterial"></UploadFile>
            </el-form-item>
            <el-form-item label="课程学时（小时）" prop="durationHour">
              <el-input-number v-model="dataForm.durationHour" :min="0" :max="1000" :step="1" step-strictly  />
            </el-form-item>
            <el-form-item label="试看时长（秒）" prop="learnDuration">
              <el-input-number v-model="dataForm.learnDuration" :min="0" :max="1000" step-strictly />
            </el-form-item>
            <el-form-item v-if="dialogFormVisible"  label="课程证书" prop="cerCourseId" >
              <el-select v-model="dataForm.cerCourseId" placeholder="请选择证书类型" clearable @change="$forceUpdate()" >
                <el-option v-for="item in cerCourseList" :key="item.id" :label="item.certName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="dialogFormVisible" label="考试证书" prop="certId" >
              <el-select v-model="dataForm.certId" placeholder="请选择证书类型" clearable @change="$forceUpdate()">
                <el-option v-for="item in this.certList" :key="item.id" :label="item.certName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="课程科目" prop="subjectId">
              <el-select v-model="dataForm.subjectId" placeholder="请选择科目">
                <el-option v-for="item in subjectList" :key="item.id" :label="item.levelName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="排序" prop="orderNo">
              <el-input-number v-model="dataForm.orderNo" :min="1"  label="排序"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" >
          <el-form-item label="课程介绍" prop="courseDesc">
            <tinymce id="courseDesc" v-if="dialogFormVisible" v-model="dataForm.courseDesc" />
          </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24" style="align-content: center" v-if="dataForm.type ==='1'">
            <Teacher ref="teacher" v-if="!operation && dialogFormVisible &&  dataForm.courseForm === '1' && dataForm.type !== '2' " :course-id="this.dataForm.id" ></Teacher>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click.native="closeDialog()">取消</el-button>
        <el-button size="mini" @click.native="saveFormData()" :loading="editLoading" type="primary">提交 </el-button>
      </div>
    </el-dialog>


    <el-drawer
        title="章节列表"
        :visible.sync="drawer"
        size="65%"
        direction="rtl">
      <Group v-if="drawer" :course-id="itemId" :type-id="typeId"></Group>
    </el-drawer>


    <el-dialog
      title="报名人数"
      :visible.sync="signUpdialog"
      width="75%"
      top="5vh" :close-on-click-modal="false"
      >
      <student v-if="signUpdialog" :ids="itemId"></student>
    </el-dialog>


    <el-dialog
      title="开课计划"
      :visible.sync="planDialog"
      width="75%"
      top="5vh"
      :close-on-click-modal="false"
    >
      <Plan v-if="planDialog" :ids="itemId" :type="typeId" :course-type="courseType" />
<!--      <son :type-id="typeId"></son>-->
    </el-dialog>


    <el-dialog
        title="折扣链接"
        top="5vh"
        :visible.sync="showDiscount"
        :close-on-click-modal="false"
    >
      <Discount v-if="showDiscount" :pid="pid" :discount-type="2"></Discount>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click.native="showDiscount=false">取消</el-button>
        <!--        <el-button size="mini" @click.native="saveFormData()" :loading="editLoading" type="primary">提交</el-button>-->
      </div>
    </el-dialog>


  </div>
</template>
<script>
import Son from './courseGroup.vue'
import Pagination from '@/components/Pagination' // 分页栏信息
import Tinymce from '@/components/CmUEditor'
import CmUpload from '@/components/CmUpload'
import Group from './courseGroup.vue'
import Teacher from './teacher.vue'
import Student from "./student.vue";
import Plan from './coursePlan.vue'
import UploadFile from '@/components/CmUploadFile'
import Discount from "@/views/exam/examDiscount.vue";
import {getCourseCert} from "@/api/modules/examApi";

export default {
  name: 'course',
  components: {
    Son,
    Discount,
    Pagination,
    CmUpload,
    Group,
    Teacher,
    Student,
    Plan,
    Tinymce,
    UploadFile,
  },
  directives: {   },
  filters: { },
  data() {
    return {
      pid:'',
      tableKey: 0,
      tableList: [],//表格数据源
      tableTotal: 0,//表格总条数数据
      listLoading: true,
      pageRequest: { pageNum: 1, pageSize: 10, },
      searchParam:{},
      orderParam:{ order_no:true,is_top:false,create_time:false, },
      certList: [],
      cerCourseList:[],
      dialogFormVisible: false,//默认不显示弹出框
      drawer: false,//默认不显示弹出框
      tableshow:false,
      operation: true, // true:新增, false:编辑
      editLoading: false,//保存表单时loading框
      signUpdialog: false,//保存表单时loading框
      planDialog: false,//保存表单时loading框
      dataFormLoading: false,//保存表单时loading框
      showDiscount: false,//保存表单时loading框
      columns: [
        {prop: 'courseName',  label: '课程名称',  sortable:false , fixed:true, width:'180' },
        {prop: 'courseImg',  label: '课程封面', sortable:false ,imgFlag:true ,fixed:true, width:'180' },
        {prop: 'orderNo',  label: '排序', sortable:false,fixed:true, width:'180' },
        {prop: 'courseForm',  label: '课程分类',  sortable:false , fixed:true, width:'100',
          tagFlag: true,tagFormatter: [
            {text:'线上',value:1,type:"success"},
            {text:'线下',value:2,type:"danger"},
          ]
        },
        {prop: 'type',  label: '课程类型',  sortable:false ,tagFlag:true , width: '160',
          tagFormatter: [
              {text:'录播课',value:'1',type:'warning'},
              {text:'直播课',value:'2',type:'success'},
            {text:'面授课',value:'3',type:'primary'},
            {text:'视频会议',value:'4',type:'danger'},
          ]
        },

        // {prop: 'classify',  label: '类别',  sortable:false  },
        {prop: 'teachAddress',  label: '上课地点',  sortable:false , width:'180' },
        // {prop: 'durationTotal',  label: '课程时长（秒）',  sortable:false , width:'180' },
        {prop: 'suitGroup',  label: '适合群体',  sortable:false , width:'180' },
        // {prop: 'courseDesc',  label: '课程介绍',  sortable:false , width:'240' },
        {prop: 'isTop',  label: '是否推荐',  sortable:false ,tagFlag: true , width:'180' ,
          tagFormatter: [
            {text:'推荐', value: '1' , type: 'success'},
            {text:'不推荐', value:'2',type: 'danger' },
          ]
        },
        {prop: 'coursePrice',  label: '课程价格',  sortable:false , width:'180' },
        {prop: 'createTime',  label: '创建时间',  sortable:false , width:'180'  },
        // {prop: 'teacher',  label: '讲师',  sortable:false  },
        {prop: 'learnCount',  label: '学习人数',  sortable:false , width:'180' },
        {prop: 'courseMaterialName',  label: '教材名称',  sortable:false , width:'180' },
        {prop: 'durationHour',  label: '课程学时（小时）',  sortable:false , width:'180' },
        // {prop: 'courseMaterial',  label: '教材下载链接',  sortable:false  },
        // {prop: 'courseLabel',  label: '课程标签',  sortable:false  },
        // {prop: 'courseDetail',  label: '课程详情',  sortable:false  },
      ],
      fileList: [],
      // 新增编辑界面数据
      dataForm: {},
      //表单检验规则
      dataFormRules: {
        courseName: [{required: true, message: '请输入课程名称', trigger: 'change'}],
        courseImg: [{required: true, message: '请上传课程封面(PC)', trigger: 'change'}],
        courseImgMobile: [{required: true, message: '请上传课程封面(Mobile)', trigger: 'change'}],
        teachAddress: [{required: true, message: '请输入上课地点', trigger: 'change'}],
        suitGroup: [{required: true, message: '请输入适合群体', trigger: 'change'}],
        courseForm: [{required: true, message: '请选择课程分类', trigger: 'change'}],
        coursePrice: [{required: true, message: '请输入课程价格', trigger: 'change'}],
        courseLabel: [{required: true, message: '请选择课程标签', trigger: 'change'}],
        type: [{required: true, message: '请选择课程类型', trigger: 'change'}],
        cerCourseId: [{required: true, message: '请选择课程证书', trigger: 'change'}],
      },
      labelOptions:[],
      teacherOption:[],
      typeOptions: [
          { value: '1', label: '录播课' },
          { value: '2', label: '直播课' },
          { value: '3', label: '面授课' },
          { value: '4', label: '视频会议' },
      ], // 初始化为空数组，动态更新
      itemId:'',
      typeId:'',
      teachers:'',
      courseType:'',
      tags:[],
      subjectList:[],

    }
  },
  created() {
    this.getList();
    this.getCertList();
    this.getCerCourseList();
    this.getSubjectList();
  },
  methods: {

    getSubjectList(){
      //【API请求】----获取表格列表数据
      this.$api.getSSubjectList({
        searchParam:{
          SEARCH_EQ_type:2,
        },
        orderParam: {
          order_no: true
        }
      }).then(response => {
        console.log(response)
        this.subjectList = response.data.content
      }).catch((res) => {
        this.$message({message: '列表获取失败', type: 'error'})
      })
    },


    //获取表格数据
    getList() {
      this.headleLabel()
      this.headleTeacher()
      // this.headleType()
      this.listLoading = true
      //【API请求】----获取表格列表数据
      this.pageRequest.orderParam = this.orderParam
      this.$api.getSCourseList(this.pageRequest).then(response => {
        this.tableList = response.data.content
        this.tableTotal = response.data.total
        this.listLoading = false;
      }).catch((res) => {
        this.$message({  message: '列表获取失败', type: 'error' })
      })
    },

    getCertList() {
      //【API请求】----获取表格列表数据
      this.$api.getZCertificateList({
        searchParam:{ SEARCH_EQ_cert_source :1},
        orderParam: {
          order_no: true
        }
      }).then(response => {
        this.certList = response.data.content
      }).catch((res) => {
      })
    },
    getCerCourseList() {
      //【API请求】----获取表格列表数据
      this.$api.getZCertificateList({
        searchParam:{ SEARCH_EQ_cert_source :2},
        orderParam: {
          order_no: true
        }
      }).then(response => {
        this.cerCourseList = response.data.content
      }).catch((res) => {
      })
    },

    // getCertRelation(id) {
    //   //【API请求】----获取表格列表数据
    //   this.$api.getCourseCert({id: id}).then(res => {
    //         console.log(res)
    //         console.log(res.data)
    //     res.data.forEach(
    //         item=>{
    //           if (item.certSource===1){
    //             // this.dataForm.certId=item.certId
    //             this.dataForm.certId = Object.assign({}, item.certId)
    //           }else{
    //             // this.dataForm.cerCourseId = item.certId
    //             this.dataForm.cerCourseId = Object.assign({}, item.certId)
    //           }
    //         }
    //     )
    //     this.dataFormLoading=false
    //     this.$nextTick(() => {
    //       this.$refs['dataForm'].clearValidate()
    //       this.editLoading = false;
    //     })
    //   }).catch(() => {
    //     this.$message({message: '未选择证书', type: 'info'})
    //     this.dataFormLoading=false
    //   })
    // },

    async getCertRelation2(id ,type) {
      //【API请求】----获取表格列表数据
      let res  = await this.$api.getCourseCert({id: id,type:type})
      console.log('res',res)
      if(res.data!==null){
        return  res.data.certId
      }else{
        return ''
      }

    },

    //表格数据筛选
    handleFilter() {
        this.pageRequest = {
            pageNum: 1,
            pageSize: 10,
        }
      this.pageRequest.searchParam = this.searchParam
      this.getList()
    },
    //【按钮点击】--- 弹出新增表单
    handleCreate() {
      this.dataFormLoading=true
      this.operation = true;
      this.initDataForm();
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.editLoading = false;
      })
      this.dataFormLoading=false
    },

    //【按钮点击】--- 弹出编辑表单
    async handleUpdate(row) {
      // this.dataFormLoading=true
      this.operation = false;

      this.dataForm = Object.assign({}, row)
      this.dataForm.courseLabel = this.dataForm.courseLabel.split(",")
      this.dataForm.teacher = this.dataForm.teacher.split(",")
      // this.getCertRelation2(row.id)
      // 同步请求
      this.dataForm.cerCourseId = await this.getCertRelation2(row.id,2 );
      this.dataForm.certId = await this.getCertRelation2(row.id ,1);
      //显示编辑菜单
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.editLoading = false;
      })

    },
    //保存表单数据
    saveFormData() {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false;
        }
        this.editLoading = true;
        //【API请求】----保存数据
        if (this.dataForm.courseLabel){
          this.dataForm.courseLabel = this.dataForm.courseLabel.join(",")
        }
        if (this.dataForm.teacher){
          this.dataForm.teacher = this.dataForm.teacher.join(",")
        }
        this.$api.saveSCourse(this.dataForm).then(() => {
          this.editLoading = false;//关闭loading框
          this.dialogFormVisible = false;//关闭表单页面
          this.initDataForm();//重置表单数据
          this.getList();//重新获取表格数据
          this.$notify({ title: '成功',  message: '保存成功', type: 'success', duration: 2000 })
        })
      })
    },
    //【按钮点击】---删除行
    handleDelete(row) {
      this.$confirm('确认删除该记录吗？', '提示', {}).then(() => {
        //【API请求】---- 删除数据
        this.$api.deleteSCourse({ids:row.id ,certId:row.certId}).then(() => {
          this.$message({  message: '操作成功', type: 'success' })
            this.pageRequest.pageNum = 1
          this.getList();
        })
      }).catch(() => {
        this.$message({  message: '操作失败', type: 'error' })
      });
    },
    //初始化表单数据，重新渲染
    initDataForm(){
      this.dataForm = {
        isTop: '' ,
        teachAddress: '' ,
        suitGroup: '' ,
        type: '' ,
        courseName: '' ,
        durationTotal: '' ,
        courseDesc: '' ,
        classify: '' ,
        id: '' ,
        certId: '',
        orderNo:'',
        cerCourseId:'',
        courseImg: '' ,
        courseImgMobile:'',
        coursePrice: '' ,
        teacher: '' ,
        learnCount: '' ,
        courseForm:'',
        courseMaterialName: ' ',
        durationHour: '' ,
        learnDuration: '' ,
        courseMaterial: '' ,
        courseLabel: '' ,
        courseDetail: '' ,
      };
    },
    //关闭表单弹出框
    closeDialog(){
      this.$refs['dataForm'].resetFields();
      this.dialogFormVisible = false
    },

    //标签
    headleLabel(){
      this.$api.getLabelOptions().then(
          res=>{
            this.labelOptions = res.data
          }
      )
    },

    headleTeacher(){
      this.$api.getTeacherOptions().then(
          res=>{
            this.teacherOption = res.data
          }
      )
    },

    // headleType(){
    //   this.$api.getTypeOptions().then(
    //       res=>{
    //         this.typeOptions = res.data
    //         for (let i = 0; i < res.data.length; i++) {
    //           let value = res.data[i].value
    //           let text = res.data[i].label
    //           let type = 'success'
    //           this.tags.push({text,value,type})
    //         }
    //         console.log(this.tags ,'tags')
    //       }
    //   )
    // },

    handleInsertItem(row){

      this.drawer = true
      this.itemId = row.id
      this.typeId = row.type
    },

    handleSignUp(row){
      this.signUpdialog = true
      this.itemId = row.id
    },

    handlePlan(row){
      this.planDialog = true
      this.itemId = row.id
      this.typeId = row.courseForm
      this.courseType = row.type
    },

    handleDiscount(row){
      this.pid=row.id
      this.showDiscount = true
    },

    // 新增方法：根据课程分类动态更新课程类型选项
    updateTypeOptions(courseForm) {
      const allTypeOptions = [
        { value: '1', label: '录播课' },
        { value: '2', label: '直播课' },
        { value: '3', label: '面授课' },
        { value: '4', label: '视频会议' },
      ];
      if (courseForm === '1') {
        // 线上课程类型
        this.typeOptions = allTypeOptions.filter(item => item.value !== '3' && item.value !== '4');
      } else if (courseForm === '2') {
        // 线下课程类型
        this.typeOptions = allTypeOptions.filter(item => item.value === '3' || item.value === '4');
      }
    },

  }


}
</script>
